//
//  LXLiveServer'.swift
//  LXWidgets
//
//  Created by zhouzuosong on 2021/2/1.
//

import Foundation

extension UserDefaults {
    
    func setItem<T: Encodable>(_ object: T, forKey key: String) {
        
        let encoder = JSONEncoder()
        guard let encoded = try? encoder.encode(object) else {
            return
        }
        
        self.set(encoded, forKey: key)
    }
    
    func getItem<T: Decodable>(_ type: T.Type, forKey key: String) -> T? {
        
        guard let data = self.data(forKey: key) else {
            return nil
        }
        
        let decoder = JSONDecoder()
        guard let object = try? decoder.decode(type, from: data) else {
            print("Couldnt find key")
            return nil
        }
        
        return object
    }
}


class LXLiveListDataManager: ObservableObject {
    static let manager = LXLiveListDataManager()
    @Published var liveListModel : LXLiveListRequestModel?
    
    var updateTime:TimeInterval = 0
    
    private init () {
        let userDefualtsData = UserDefaults(suiteName: isDemoProject ? "group.widget.swiftui.demo" : (isZKApp ? "group.lexue.zhongkao" : "group.lexue.gaokao"))
        let liveListModel : LXLiveListRequestModel? = userDefualtsData?.getItem(LXLiveListRequestModel.self, forKey: "liveListModel")
        self.liveListModel = liveListModel
    }
    
    
    

    class func getLiveListData() -> Void {
        LXLiveServer.getLiveList { (result,data) in
//            var resultDic : Dictionary<String,Any> = result as! Dictionary<String,Any>
//
//            let modelData = LXLiveListRequestModel.getModel(data: data)
            
            do {
                let jsonData : Data = data

                let jsonObject:NSMutableDictionary = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! NSMutableDictionary
                
                let code:Int = jsonObject["code"] as! Int
                
                if code != 0 {
                    print("请求失败")
                    return
                }
                
                let jsonListObject: AnyObject = jsonObject["data"] as AnyObject
                
                if let jsonListData = try? JSONSerialization.data(withJSONObject: jsonListObject, options: []){
                    
                    let dicArr = try! JSONSerialization.jsonObject(with: jsonListData, options: .allowFragments) as! [[String:AnyObject]]
                    
                    if dicArr.count > 0 {
                        manager.saveDictionaryDataToLocal(liveTimeListData: jsonListData)
                        manager.updateTime = Date().timeIntervalSince1970
                    }
                }
            }
            catch {
                print("catch error")
            }

        } failure: { (error) in
            print("请求失败")
        }
    }
    
    class func haveLiveCourse(with date:Date) -> Bool {
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyyMMdd"
        let localList:[LXLiveCourseModel]? = LXLiveListDataManager.getLocalList()
        
        
        if let liveListModelList = localList {
            for liveDateItem in liveListModelList {
                let itemDate = Date(timeIntervalSince1970: liveDateItem.day/1000)

                if dformatter.string(from: itemDate) == dformatter.string(from: date) {
                    print("它们是同一天")
                    return true
                }else {
                    print("它们不是同一天")
                }
            }
        }else{
            print("没数据 D")
        }

        return false
    }
    
    func haveLiveCourse(with date:Date) -> Bool {
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyyMMdd"

        if let liveListModelList = LXLiveListDataManager.manager.liveListModel?.data {
            for liveDateItem in liveListModelList {
                let itemDate = Date(timeIntervalSince1970: liveDateItem.day/1000)

                if dformatter.string(from: itemDate) == dformatter.string(from: date) {
                    print("它们是同一天")
                    return true
                }else {
                    print("它们不是同一天")
                }
            }
        }

        return false
    }
    
    func saveDictionaryDataToLocal(liveTimeListData:Data?) -> Void {
        
        if let timeData = liveTimeListData {
            /// 保存到本地
            let userDefualtsData = UserDefaults(suiteName: isDemoProject ? "group.widget.swiftui.demo" : (isZKApp ? "group.lexue.zhongkao" : "group.lexue.gaokao"))
            userDefualtsData?.setValue(timeData, forKey: "liveTimeList")
            print("已保存到本地")
            
            self.updateTime = Date().timeIntervalSince1970
            print("数据更新时间已更新")
        }else{
            print("数据为空 暂未保存")
        }
    }
    
    class func getLocalList() -> [LXLiveCourseModel] {
        let userDefualtsData = UserDefaults(suiteName: isDemoProject ? "group.widget.swiftui.demo" : (isZKApp ? "group.lexue.zhongkao" : "group.lexue.gaokao"))
        
        let localModelListData : Data? = userDefualtsData?.data(forKey: "liveTimeList")
        var localModelList: [LXLiveCourseModel] = []

        if localModelListData == nil {
            return localModelList
        }
        
        do {
            let localDicArray = try JSONSerialization.jsonObject(with: localModelListData!, options: .allowFragments) as! [[String:AnyObject]]
            
            for courseItem in localDicArray {
                
                let courseModel = LXLiveCourseModel()
                courseModel.day = courseItem["day"] as! Double
                courseModel.dayStr = courseItem["dayStr"] as! String
                
                let liveLessonIdsObjc = courseItem["liveLessonIds"] as AnyObject
                if let liveLessonIdsData = try? JSONSerialization.data(withJSONObject: liveLessonIdsObjc, options: []){
                    
                    let liveLessonIdsArray = try JSONSerialization.jsonObject(with: liveLessonIdsData, options: .allowFragments) as! [NSNumber]
                    
                    var liveLessonIdsStringArray:[String] = []
                    
                    for timeNumber in liveLessonIdsArray {
                        liveLessonIdsStringArray.append(timeNumber.stringValue)
                    }
                    courseModel.liveLessonIds = liveLessonIdsStringArray
                    
                }
                
                // 添加到指定数组
                localModelList.append(courseModel)
            }
        }
        catch {
            print("test catch ")
        }
        
        if localModelList.count > 0 {
            print("本地有数据")
        }

        return localModelList
    }
}

class LXLiveServer : Codable {
    
    class func getLiveList(success: @escaping ((_ result: Any, _ data:Data) -> ()),failure: @escaping ((_ error: Error) -> ())) {
        let path:String = "https://zkapisdev.lexue.com/lexuelearn/live-schedule/v1/month/live/lessons/stat/2021/5"
        
        LXRequest().getWithPath(path: path, paras: nil, success: success, failure: failure)
    }
}


class LXRequestRespondsBaseModel: NSObject, Codable {
    var code : Int = 0
    var message : String?
    var success : Bool = false

    /// 字典转模型
    class func toModel<T>(_ type: T.Type, value: Any?) -> T? where T: Decodable {
        guard let value = value else { return nil }
        return toModel(type, value: value)
    }
    /// 字典转模型
    class func toModel<T>(_ type: T.Type, value: Any) -> T? where T : Decodable {
        guard let data = try? JSONSerialization.data(withJSONObject: value) else { return nil }
        let decoder = JSONDecoder()
        decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+Infinity", negativeInfinity: "-Infinity", nan: "NaN")
        return try? decoder.decode(type, from: data)
    }
    
    // 字典转模型
    class func decode<T>(json:Any)->T? where T:Decodable{
        do {
            let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
            let model = try JSONDecoder().decode(T.self, from: data)
            return model
        } catch let err {
            print(err)
            return nil
        }
    }

    // 模型转字典
    class func encode<T>(model:T) ->Any? where T:Encodable {
        do {
            let tdata = try JSONEncoder().encode(model)
            let tdict  = try JSONSerialization.jsonObject(with: tdata, options: JSONSerialization.ReadingOptions.allowFragments)
            return tdict
        } catch let error {
            print(error)
            return nil
        }
    }
}

class LXLiveListRequestModel: LXRequestRespondsBaseModel, ObservableObject {
    
    @Published var data : [LXLiveCourseModel] = [LXLiveCourseModel]()
    
    // 字典转模型
    override class func decode<T>(json:Any)->T? where T:Decodable{
        do {
            let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
            let model = try JSONDecoder().decode(T.self, from: data)
            return model
        } catch let err {
            print(err)
            return nil
        }
    }

    // 模型转字典
    override class func encode<T>(model:T) ->Any? where T:Encodable {
        do {
            let tdata = try JSONEncoder().encode(model)
            let tdict  = try JSONSerialization.jsonObject(with: tdata, options: JSONSerialization.ReadingOptions.allowFragments)
            return tdict
        } catch let error {
            print(error)
            return nil
        }
    }
}

class LXLiveCourseModel:ObservableObject,Codable {
    var day : Double = 0
    var dayStr : String = ""
    var liveLessonIds : [String] = []
}
